package com.lagou.rpc.consumer.client;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class ZkClient {

    @Autowired
    private CuratorFramework curatorFramework;

    private final static String SERVER_PATH = "/server";

    public void createOrUpdatePath(String path, String data){
        try {
            Stat stat = curatorFramework.checkExists().forPath(path);
            if(stat == null) {
                if (null == data) {
                    curatorFramework.create().creatingParentsIfNeeded().forPath(path);
                } else {
                    curatorFramework.create().creatingParentsIfNeeded().forPath(path, data.getBytes(StandardCharsets.UTF_8));
                }
            }else if (null != data){
                curatorFramework.setData().forPath(path,data.getBytes(StandardCharsets.UTF_8));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createOrUpdatePath(String path){
        createOrUpdatePath(path,null);
    }

    public List<String> getServerList() throws Exception {
        List<String> serverList = curatorFramework.getChildren().forPath(SERVER_PATH);
        return serverList;
    }

    public void setServerPathChildrenListener(PathChildrenCacheListener listener){
        PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework,SERVER_PATH,false);

        pathChildrenCache.getListenable().addListener(listener);

        try {
            pathChildrenCache.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public CuratorFramework getCuratorFramework() {
        return curatorFramework;
    }
}
